"""
1-7月各街道矛盾纠纷堆积图
"""

import matplotlib.pyplot as plt
import numpy as np

years = [
    "一月",
    "二月",
    "三月",
    "四月",
    "五月",
    "六月",
    "七月",
    "八月",
    "九月",
    "十月",
    "十一月",
    "十二月",
]
base_data = {
    "凌水": [81, 81, 76, 77, 138, 164, 125, 72],
    "龙王塘": [27, 25, 25, 26, 86, 66, 93, 23],
    "七贤岭": [110, 106, 93, 86, 91, 58, 110, 23],
}
labels = list(base_data.keys())
data = np.array(list(base_data.values()))
colors = ["#4f80bd", "#c0504d", "#9bbb59"]
# sum_data = [sum(x) for x in data]

months = years[: len(data[0])]

# 绘制堆积图
fig, axs = plt.subplots(figsize=(10, 7))  # 生产1个子图
plt.subplots_adjust(bottom=0.3)  # 首先要加大底部空间，否则表格会显示不全
axs.stackplot(months, data, labels=labels, colors=colors)

# 计算table
# 行求和后，作为新列加入源数据
row_sums = np.sum(data, axis=1, keepdims=True)
data_with_row_sums = np.hstack((data, row_sums))

# 列求和后，作为新行加入
col_sums = np.sum(data_with_row_sums, axis=0, keepdims=True)
final_data = np.vstack((data_with_row_sums, col_sums))

# 4. 绘制表格
labels.append("累计")
months.append("累计")
axs.table(
    cellText=final_data,
    colLabels=months,
    rowLabels=labels,
    loc="bottom",
    cellLoc="center",
    bbox=[
        0,
        -0.4,
        1,
        0.3,
    ],  # 调整表格和X轴的距离，意味着表格将从轴宽度的0%处(x原点）、从x轴下方0.4（y原点）开始，自动设置宽度，并且高度为0.3。
)

axs.legend(loc="upper left")
axs.grid(True)

axs.margins(0, 0)  # x轴和y轴不预留空白，不预留空白

axs.set_title(
    f"1-{len(months)-1}月街道矛盾纠纷排查量",
    fontsize=20,
    # fontstyle="oblique",
    fontweight="bold",
)
axs.set_ylabel("矛盾纠纷排查量")

# 设置中文用楷体
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False  # 解决负号'-'显示为方块的问题

# 显示图形
plt.show()
